#!/bin/bash

# disable-passwordless-sudo.sh
# 功能说明:
# 1. 移除一个或多个用户的免密码 sudo 配置。
# 2. 支持通过命令行传入用户名列表，如果未传入参数，则默认操作当前用户。
# 3. 删除 /etc/sudoers 文件中与用户相关的配置行。
# 4. 删除 /etc/sudoers.d/ 目录中与用户相关的独立配置文件。
# 5. 输出每个用户的移除结果，包括成功与否的具体信息。

remove_passwordless_sudo() {
  local user="$1"

  echo "Removing passwordless sudo configuration for user: $user"

  # 检查 /etc/sudoers 文件
  if sudo grep -q "$user ALL=(ALL) NOPASSWD: ALL" /etc/sudoers; then
    echo "Found passwordless sudo entry in /etc/sudoers"
    sudo sed -i "/$user ALL=(ALL) NOPASSWD: ALL/d" /etc/sudoers
    echo "Removed from /etc/sudoers"
  else
    echo "No passwordless sudo entry found in /etc/sudoers"
  fi

  # 检查 /etc/sudoers.d/ 配置文件
  local sudoers_file="/etc/sudoers.d/$user"
  if [[ -f "$sudoers_file" ]]; then
    echo "Found passwordless sudo file: $sudoers_file"
    sudo rm -f "$sudoers_file"
    echo "Removed $sudoers_file"
  else
    echo "No passwordless sudo file found in /etc/sudoers.d/"
  fi

  echo "Passwordless sudo configuration removed for $user"
}

main() {
  # 检查是否为非 root 用户运行
  if [[ $EUID -eq 0 ]]; then
    echo "This script must be run as a non-root user"
    exit 1
  fi

  # 如果没有传入用户名，则默认操作当前用户
  if [[ $# -eq 0 ]]; then
    echo "No usernames provided. Defaulting to the current user: $USER"
    remove_passwordless_sudo "$USER"
  else
    # 遍历所有传入的用户名
    for user in "$@"; do
      if id "$user" &>/dev/null; then
        remove_passwordless_sudo "$user"
      else
        echo "User $user does not exist on this system."
      fi
    done
  fi
}

# 运行主函数
main "$@"

